package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"message/api/request"
	"message/glodal"
	"message/inits"
	"message/model"
	"message/pkg"
	"net/http"
	"time"
)

func Register(context *gin.Context) {
	var req request.User
	err := context.ShouldBind(&req)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数错误",
		})
		return
	}
	var user model.User
	glodal.DB.Where("mobile = ?", req.Mobile).First(&user)
	if user.ID != 0 {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "该用户已存在",
		})
		return
	}
	m := model.User{
		Mobile: req.Mobile,
		Passwd: pkg.MD5(req.Passwd),
	}
	glodal.DB.Create(&m)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "注册成功",
		"data":    m.ID,
	})
}

func List(context *gin.Context) {
	var req request.List
	err := context.ShouldBind(&req)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数错误",
		})
		return
	}
	var users []model.User
	glodal.DB.Find(&users)
	marshal, err := json.Marshal(users)
	if err != nil {
		return
	}
	glodal.Rdb.Set(inits.Ctx, "userList", marshal, time.Hour*24)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查询成功",
		"data":    users,
	})
}

func Announcement(context *gin.Context) {
	var req request.Announcement
	err := context.ShouldBind(&req)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数错误",
		})
		return
	}
	var announcement model.Announcement
	glodal.DB.Where("user_id = ?", req.UserId).First(&announcement)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查看成功",
		"data":    announcement,
	})
}

func Shop(context *gin.Context) {
	var req request.Shop
	err := context.ShouldBind(&req)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数错误",
		})
		return
	}
	ping := model.Ping{
		ShopId:  req.ShopId,
		UserId:  req.UserId,
		Content: req.Content,
	}
	rabbitmq := pkg.NewRabbitMQSimple("shop")
	marshal, err := json.Marshal(ping)
	if err != nil {
		return
	}
	rabbitmq.PublishSimple(string(marshal))
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "消息已通知",
	})
}
